package cn.org.seventh.tools.plugin;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;
import java.net.URL;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
import org.generama.AbstractTemplateEngine;
import org.generama.GeneramaException;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

public class XmlFormatedFreeMarkerTemplateEngine extends AbstractTemplateEngine {
	public void generate(Writer out, Map contextObjects, String encoding,
			Class pluginClass) {
		URL url = getScriptURL(pluginClass, ".ftl");
		try {
			InputStream scriptStream = url.openStream();
			Reader reader = new InputStreamReader(scriptStream);
			Template template = new Template(url.toExternalForm(), reader,
					Configuration.getDefaultConfiguration(), encoding);
			StringWriter writer = new StringWriter();
			template.process(contextObjects, writer);
			writer.flush();
			Document document = DocumentHelper.parseText(writer.getBuffer()
					.toString());
			OutputFormat format = OutputFormat.createCompactFormat();
			format.setEncoding("UTF-8");
			format.setNewlines(true);
			format.setIndent(true);
			XMLWriter xmlWriter = new XMLWriter(out, format);
			xmlWriter.write(document);
			xmlWriter.flush();
		} catch (IOException e) {
			throw new GeneramaException(e.getMessage(), e);
		} catch (TemplateException e) {
			throw new GeneramaException(e.getMessage(), e);
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
